<?php

namespace Respect\Environment;

class PhpCgiCompatibleEnv extends CallbackEnv implements EnvironmentableInterface
{

    protected $fixedHeaders = array();

    protected function getFixedHttpAuth()
    {
        if (function_exists('apache_request_headers')) {
            $rh = apache_request_headers();
            if (isset($rh['Authorization'])) {
                return $this->fixedHeaders['HTTP_AUTHORIZATION'] = $rh['Authorization'];
            }
        } elseif (isset($_SERVER['PHP_AUTH_USER'])) {
            return $this->fixedHeaders['HTTP_AUTHORIZATION'] = 'Basic ' . base64_encode($_SERVER['PHP_AUTH_USER']
                . ':' . $_SERVER['PHP_AUTH_PW']);
        } elseif (isset($_SERVER['PHP_AUTH_DIGEST'])) {
            return $this->fixedHeaders['HTTP_AUTHORIZATION'] = 'Digest ' . $_SERVER['PHP_AUTH_DIGEST'];
        }
    }

    protected function getFixed($varname)
    {
        switch ($varname) {
            case 'HTTP_AUTHORIZATION':
                return $this->getFixedHttpAuth();
                break;
            default:
                return false;
        }
    }

    public function __invoke($varname)
    {
        return getenv($varname) ? : $this->getFixed($varname);
    }

    public function offsetGet($varname)
    {
        return getenv($varname) ? : $this->getFixed($varname);
    }

    public function __get($varname)
    {
        return getenv($varname) ? : $this->getFixed($varname);
    }

}